import React, { useEffect, useState } from "react";
import { Table, Divider, Button } from "antd";
import { Link } from 'react-router-dom';
import { InboxOutlined } from '@ant-design/icons';
import axios from 'axios';
import {Modal, Spin,Form,Upload,Input} from 'antd';
import './index.css'


const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 14,
  },
};
const columns = [
    {
      title: 'name',
      dataIndex: '0',
      key: "column1",
      render: (text) => <Link to={`/jbrowse?kronaSpecise=${text}`}>{text}</Link>,
    },
    {
      title: 'taxonomy_id',
      dataIndex: '1',
      key: "column2",
      render: (text) => <Link to={`/jbrowse?kronaSpecise=${text}`}>{text}</Link>,
    },
    {
      title: 'taxonomy_lvl',
      dataIndex: '2',
      key: "column3",
    },
    {
      title: 'kraken_assigned_reads',
      dataIndex: '3',
      key: "column4",
    },
    {
      title: 'added_reads',
      dataIndex: '4',
      key: "column5",
    },
    {
      title: 'new_est_reads',
      key: "column5",
      dataIndex: '6',
    },
    {
      title: 'fraction_total_reads',
      key: "column6",
      dataIndex: '7',
    },
]

const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
},
  // getCheckboxProps: (record) => ({
  //   disabled: record.name === 'Disabled User',
  //   // Column configuration not to be checked
  //   name: record.name,
  // }),
};

function App() {
  const [data, setData] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const onSelectChange = (newSelectedRowKeys) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  useEffect(() => {
          async function fetchData() {
            const response = await fetch('./1.txt');
            const text = await response.text();
            const rows = text.split('\n').map(row => row.split('\t'));
            const newArray = rows.slice(1);
            newArray.pop();
            setData(newArray);
          }
          fetchData();
        }, []);

        const [isModalOpen, setIsModalOpen] = useState(false); 
        const showModal = () => {
          setIsModalOpen(true);
        };
        const handleOk = () => {
          setIsModalOpen(false);
        };
        const handleCancel = () => {
          setIsModalOpen(false);
        };
        
        const normFile = (e) => {
          console.log('Upload event:', e);
          if (Array.isArray(e)) {
            return e;
          }
          return e?.fileList;
        };
        const onFinish = (values) => {
          if(values.dragger==undefined){
            alert('please input file！')
            return
          }
          setLoading(true);      
          const file = values.dragger[0].originFileObj
          let data =new FormData()
          data.append("file",file) 
          useEffect(() => {
                    async function fetchData() {
                      const response = await fetch('./1.txt');
                      const text = await response.text();
                      const rows = text.split('\n').map(row => row.split('\t'));
                      const newArray = rows.slice(1);
                      newArray.pop();
                      setData(newArray);
                    }
                    fetchData();
                  }, []);
          // axios({
          //   headers: {
          //     'Content-Type':'application/json'
          //   },
          //     method: 'post',
          //     url:`http://127.0.0.1:5000/index/upload`,
          //     data: data,
          //   }).then(res => {
          //     setLoading(false);
          //     setIsModalOpen(false);
          //     if(res && res.status === 200){
          //       console.log(res)
          //       const element = document.createElement("a");
          //       const file = new Blob([res.data], {type: 'text/html'});
          //       element.href = URL.createObjectURL(file);
          //       setData(element.href)
          //       useEffect(() => {
          //         async function fetchData() {
          //           const response = await fetch('./1.txt');
          //           const text = await response.text();
          //           const rows = text.split('\n').map(row => row.split('\t'));
          //           const newArray = rows.slice(1);
          //           newArray.pop();
          //           setData(newArray);
          //         }
          //         fetchData();
          //       }, []);
          //     }else{
          //       console.log('error')
          //     }
          //   })
        };

        const handleChange = (event) => {
          setSearchTerm(event.target.value);
          console.log(data)
          const results = data.filter((row) =>
          row[0].toLowerCase().includes(searchTerm.toLowerCase())
        );
        setData(results);
        };
      const clearSearch = () => {
        setSearchTerm("");
        useEffect(() => {
          async function fetchData() {
            const response = await fetch('./1.txt');
            const text = await response.text();
            const rows = text.split('\n').map(row => row.split('\t'));
            const newArray = rows.slice(1);
            newArray.pop();
            setData(newArray);
          }
          fetchData();
        }, []);
      };
  return (
    <div>
    <div style={{alignItems:"center"}}>
      <Input placeholder="请输入搜索内容"  className='ant-INput'  value={searchTerm} onChange={handleChange} />
      <Button className="ant-btn2" onClick={clearSearch}>Clear</Button>
      <Button className="ant-btn2" onClick={showModal} >Upload File</Button>
      </div>
      <Modal title="Basic Modal" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} 
      cancelButtonProps={{ style: { display: "none" } }} // 隐藏取消按钮
      okButtonProps={{ style: { display: "none" } }} // 隐藏确认按钮
      >
      <Spin spinning={loading}>  
      <Form
            name="validate_other"
            {...formItemLayout}
            onFinish={onFinish}
            style={{
              maxWidth: 600,
            }}
          >
            <Form.Item label="Dragger">
              <Form.Item name="dragger" valuePropName="fileList" getValueFromEvent={normFile} noStyle>
                <Upload.Dragger name="files" action="/upload.do" >
                  <p className="ant-upload-drag-icon">
                    <InboxOutlined />
                  </p>
                  <p className="ant-upload-text">Click or drag file to this area to upload</p>
                </Upload.Dragger>
              </Form.Item>
            </Form.Item>

            <Form.Item
              wrapperCol={{
                span: 12,
                offset: 6,
              }}
            >
              <Button type="primary" htmlType="submit" >
                Submit
              </Button>
            </Form.Item>
        </Form></Spin>
      </Modal>
      <Divider />
    <Table
    // rowSelection={rowSelection}
     columns={columns} dataSource={data} pagination={{ pageSize: 15}} rowKey="column2"/>
    </div>
  )
}

export default App